/**
 *Copyright (c) 2024 watereyes
 * workflow is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.workflow.common.service.impl;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.koron.workflow.common.service.MailSendService;

@Service
public class JavamailServiceImpl implements MailSendService{
	
	private static final Logger LOGGER = LoggerFactory.getLogger(JavamailServiceImpl.class);
	
	@Value("${email.host}")
	private String host;
	@Value("${email.from}")
	private String from;
	@Value("${email.username}")
	private String username;
	@Value("${email.password}")
	private String password;
	private static final String TITLE = "流程平台催办";
	private static final String PERSONAL = "系统管理员";

	public boolean sendMail(String toEmail, String content) {
		try {
			Address[] address = new InternetAddress[] {new InternetAddress(toEmail)};
			send(address, content);
			return true;
		} catch (AddressException ex) {
			LOGGER.error("邮件地址有误,发送邮件失败!", ex);
		}catch (MessagingException ex) {
			LOGGER.error("发送邮件失败!", ex);
		}catch (UnsupportedEncodingException ex) {
			LOGGER.error("发送邮件失败!", ex);
		}
		return false;
	}

	public boolean sendMail(List<String> toEmails, String content) {
		Address[] address = new InternetAddress[toEmails.size()];
		int i;
		try {
			for (i = 0; i < toEmails.size(); i++) {
				String email = toEmails.get(i);
				address[i] = new InternetAddress(email);
			}
			send(address, content);
			return true;
		} catch (AddressException ex) {
			LOGGER.error("邮件地址有误,发送邮件失败!", ex);
		}catch (MessagingException ex) {
			LOGGER.error("发送邮件失败!", ex);
		}catch (UnsupportedEncodingException ex) {
			LOGGER.error("发送邮件失败!", ex);
		}
		return false;
	}

	private void send(Address[] address, String content) throws MessagingException, UnsupportedEncodingException {
		Properties properties = new Properties();
		properties.put("mail.smtp.host", host);
		properties.put("mail.smtp.auth", "true"); // 这样才能通过验证
		Session session = Session.getDefaultInstance(properties);

		session.setDebug(true);

		MimeMessage message = new MimeMessage(session);
		message.setFrom(new InternetAddress(from, PERSONAL, "utf-8"));

		message.setRecipients(Message.RecipientType.TO, address);

		message.setSentDate(new Date());
		message.setSubject(MimeUtility.encodeText(TITLE, MimeUtility.mimeCharset("UTF-8"), null));  
		message.setContent(content, "text/html;charset=UTF-8"); // 设置邮件格式  
		message.saveChanges();
		Transport transport = session.getTransport("smtp");
		transport.connect(host, username, password);
		transport.sendMessage(message, message.getAllRecipients());
		transport.close();
	}

}
